// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function parseUri (str) {
    var o   = parseUri.options,
	m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
	uri = {},
	i   = 14;
	
	while (i--) uri[o.key[i]] = m[i] || "";
	
	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	    });
	
	return uri;
};

parseUri.options = {
    strictMode: false,
    key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
    q:   {
	name:   "queryKey",
	parser: /(?:^|&)([^&=]*)=?([^&]*)/g
    },
    parser: {
	strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
	loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
    }
};

// Note: this must match LibraryManager::clean_label()
function clean_label(label) {
    var clean = label.toLowerCase();
    clean = clean.replace(new RegExp(/[ \/]/g), '-');
    clean = clean.replace(new RegExp(/[)(]/g), '');
    return clean;
}

function RequestTopics() {
    var prefs = new gadgets.Prefs();
    var label = clean_label(prefs.getString("label"));
    var library_url = prefs.getString("library_url")
    var query = label ? ('?q=' + label) : ''
    var params = {};
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 0;
    var url = "http://global-learning-portal-2.appspot.com/admin/library/topics" + query;
    var callback = function(obj) {
	TopicCallback(library_url, obj.data);
    }
    gadgets.io.makeRequest(url, callback, params);
}

function TopicSorter(a, b) {
    return a[1].toLocaleLowerCase().localeCompare(b[1].toLocaleLowerCase());
}

// TODO(sdd): dynamic height
function TopicCallback(library_url, data) {
    var prefs = new gadgets.Prefs();
    var label = clean_label(prefs.getString("label"));
    if (label) { label += "+"; }
    var html = "";
    var topics = data.sort(TopicSorter);
    for (var i in topics) {
	var topic = topics[i];
	var topic_label = topic[0];
	var pretty = topic[1];
	html += "<li><a href=\"" + library_url + "?mode=slice&q=" + label +
	    topic_label + "\" target=\"_top\">" + pretty + "</a></li>\n";
    }
    if (topics.length == 0) {
	html = "<li><em>No topics found.</em></li>";
    }
    document.getElementById('topics').innerHTML = html;
    gadgets.window.adjustHeight();
}

gadgets.util.registerOnLoadHandler(RequestTopics);
